<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['border_bottom', r1 === 0 ? 'border_top' : '', 'v-center']" v-for="(right_one, r1) in scope.row.children" :key="right_one.id" :this-index="r1">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag>{{right_one.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级和三级权限-->
              <el-col :span="19">
                <!--通过 for 循环 嵌套渲染二级权限-->
                <el-row :class="[r2 === 0 ? '' : 'border_top', 'v-center']" v-for="(right_two, r2) in right_one.children" :key="right_two.id" :this-index="r2">
                  <el-col :span="6">
                    <el-tag type="success">{{right_two.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级权限-->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(right_three, r3) in right_two.children" :key="right_three.id" :this-index="r3" closable @close="removeRightById(scope.row, right_three.id)">
                      {{right_three.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--<pre>{{scope.row}}</pre>-->
            <!-- 数据列表 -->
            <!--{
            "id": 30,
            "roleName": "主管",
            "roleDesc": "技术负责人",
            "children": [
            {
            "id": 101,
            "authName": "商品管理",
            "path": "goods",
            "children": [
            {
            "id": 104,
            "authName": "商品列表",
            "path": "goods",
            "children": [
            {
            "id": 116,
            "authName": "商品修改",
            "path": "goods"
            }
            ]
            },
            {
            "id": 115,
            "authName": "分类参数",
            "path": "params",
            "children": [
            {
            "id": 142,
            "authName": "获取参数列表",
            "path": "categories"
            },
            {
            "id": 143,
            "authName": "创建商品参数",
            "path": "categories"
            },
            {
            "id": 144,
            "authName": "删除商品参数",
            "path": "categories"
            }
            ]
            },
            {
            "id": 121,
            "authName": "商品分类",
            "path": "categories",
            "children": [
            {
            "id": 122,
            "authName": "添加分类",
            "path": "categories"
            },
            {
            "id": 123,
            "authName": "删除分类",
            "path": "categories"
            },
            {
            "id": 149,
            "authName": "获取分类详情",
            "path": "categories"
            }
            ]
            }
            ]
            },
            {
            "id": 102,
            "authName": "订单管理",
            "path": "orders",
            "children": [
            {
            "id": 107,
            "authName": "订单列表",
            "path": "orders",
            "children": [
            {
            "id": 109,
            "authName": "添加订单",
            "path": "orders"
            }
            ]
            }
            ]
            },
            {
            "id": 103,
            "authName": "权限管理",
            "path": "rights",
            "children": [
            {
            "id": 111,
            "authName": "角色列表",
            "path": "roles",
            "children": [
            {
            "id": 129,
            "authName": "添加角色",
            "path": "roles"
            },
            {
            "id": 130,
            "authName": "删除角色",
            "path": "roles"
            },
            {
            "id": 134,
            "authName": "角色授权",
            "path": "roles"
            },
            {
            "id": 135,
            "authName": "取消角色授权",
            "path": "roles"
            },
            {
            "id": 138,
            "authName": "获取角色列表",
            "path": "roles"
            },
            {
            "id": 139,
            "authName": "获取角色详情",
            "path": "roles"
            },
            {
            "id": 140,
            "authName": "更新角色信息",
            "path": "roles"
            },
            {
            "id": 141,
            "authName": "更新角色权限",
            "path": "roles"
            }
            ]
            },
            {
            "id": 112,
            "authName": "权限列表",
            "path": "rights",
            "children": [
            {
            "id": 147,
            "authName": "查看权限",
            "path": "rights"
            }
            ]
            }
            ]
            },
            {
            "id": 125,
            "authName": "用户管理",
            "path": "users",
            "children": [
            {
            "id": 110,
            "authName": "用户列表",
            "path": "users",
            "children": [
            {
            "id": 131,
            "authName": "添加用户",
            "path": "users"
            },
            {
            "id": 132,
            "authName": "删除用户",
            "path": "users"
            },
            {
            "id": 133,
            "authName": "更新用户",
            "path": "users"
            },
            {
            "id": 136,
            "authName": "获取用户详情",
            "path": "users"
            },
            {
            "id": 137,
            "authName": "分配用户角色",
            "path": "users"
            }
            ]
            }
            ]
            },
            {
            "id": 145,
            "authName": "数据统计",
            "path": "reports",
            "children": [
            {
            "id": 146,
            "authName": "数据报表",
            "path": "reports",
            "children": [
            {
            "id": 148,
            "authName": "查看数据",
            "path": "reports"
            }
            ]
            }
            ]
            }
            ]
            }-->
          </template>
        </el-table-column>
        <!-- 索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px" v-slot="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
          <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配权限的对话框-->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" @close="setRightDialogClosed" width="50%">
      <el-tree :data="allRightsList" :props="rightTreeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 显示权限分配对话框
      setRightDialogVisible: false,
      // 所有权限的数据
      allRightsList: [],
      // 树形控件的属性绑定对象
      rightTreeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的keys 数组,这里也就是三级权限的id
      defaultKeys: [],
      // 保存当前操作的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList () {
      const { data: result } = await this.$http.get('roles')

      if (result.meta.status !== 200) {
        this.$message.error('get role list failed!')
      }

      this.rolesList = result.data
    },
    // 删除权限通过id
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm(
        'are you sure delete this right?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('cancel to delete this right: ' + role.authName)
      }

      const { data: result } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      if (result.meta.status !== 200) {
        return this.$message.error('delete this right failed!')
      }

      // this.getRolesList() // 会发生页面的完整渲染，导致刷新页面
      role.children = result.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      // 获取所有权限的数据
      const { data: result } = await this.$http.get('rights/tree')

      if (result.meta.status !== 200) {
        return this.$message.error('get rights data failed!')
      }

      // 把获取的数据保存到
      this.allRightsList = result.data
      // console.log(this.allRightsList)
      // 调用递归 getLeafKeys 获取三级id
      this.getLeafKeys(role, this.defaultKeys)
      // 设置当前角色id
      this.roleId = role.id
      this.setRightDialogVisible = true
    },
    // 递归，获取角色下所有的三级权限id，并保存在 defaultKeys 数组中
    getLeafKeys (node, arr) {
      // 如果当前 node 节点不包含children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 关闭对话框，清空数据
    setRightDialogClosed () {
      this.roleId = ''
      this.defaultKeys = []
    },
    // 为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(this.$refs)
      // console.log(keys)

      const idStr = keys.join(',')
      const { data: result } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })

      if (result.meta.status !== 200) {
        return this.$message.error('allot right failed!')
      }

      this.$message.success('allot right success!')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .border_top {
    border-top: 1px solid #eeeeee;
  }

  .border_bottom {
    border-bottom: 1px solid #eeeeee;
  }

  .v-center {
    display: flex;
    align-items: center;
  }
</style>
